<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="usersList" style="width: 100%" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="toggleUserStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="180px" label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑角色" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="operate(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除角色" placement="top">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="delectUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="setRolesRight(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryinfo.pagenum"
        :page-sizes="[2, 5,10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户弹出框 -->
    <el-dialog title="添加用户" :visible.sync="addVisible" width="50%">
      <el-form :model="addForm" :rules="addrules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddUser">取 消</el-button>
        <el-button type="primary" @click="addUser(addForm)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户资料 -->
    <el-dialog title="修改用户" :visible.sync="operateUser" width="30%" @close="close">
      <el-form
        :model="temporaryuser"
        :rules="addrules"
        ref="temporaryuserRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="temporaryuser.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temporaryuser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temporaryuser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="operateUser = false">取 消</el-button>
        <el-button type="primary" @click="operateUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹出框 -->
    <el-dialog title="分配角色" :visible.sync="rolesRightVisible" width="30%">
      <p>姓名：{{currentUser.username}}</p>
      <p>当前角色：{{currentUser.role_name}}</p>
      <el-form v-model="currentRolesValue" ref="setRolesRef">
        <el-form-item label="分配角色">
          <el-select v-model="currentRolesValue" placeholder="请选择">
            <el-option
              v-for="item in roleslist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import loginVue from "./login.vue";
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const emailReg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (!emailReg.test(value)) {
          callback(new Error("请输入正确email"));
        } else {
          callback();
        }
      }, 0);
    };
    var checkmoblie = (rule, value, callback) => {
      const moblieReg = /0?(13|14|15|18|17)[0-9]{9}/;
      if (!value) {
        return callback(new Error("电话不能为空"));
      }
      setTimeout(() => {
        if (!moblieReg.test(value)) {
          callback(new Error("请输入正确手机号"));
        } else {
          callback();
        }
      }, 0);
    };
    return {
      usersList: [],
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      addVisible: false,
      rolesRightVisible: false,
      operateUser: false,
      total: 0,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      temporaryuser: {},
      addrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkmoblie, trigger: "blur" }
        ]
      },
      roleslist: [],
      currentUser: {},
      currentRolesValue: ""
    };
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo
      });
      if (res.meta.status !== 200) return this.$message.error("获取列表失败");
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newpage) {
      this.queryinfo.pagesize = newpage;
      this.getUsersList();
    },
    handleCurrentChange(newpage) {
      this.queryinfo.pagenum = newpage;
      this.getUsersList();
    },
    async toggleUserStatus(userinfo) {
      const { data: res } = await this.$http.put(
        `users/` + userinfo.id + `/state/` + userinfo.mg_state + ``
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("修改用户状态失败");
      }
      this.$message.success("修改用户状态成功");
    },
    addUser(userinfo) {
      this.$refs.addFormRef.validate(async config => {
        this.addVisible = false;
        if (!config) {
          this.$refs.addFormRef.resetFields();
          return;
        }
        const { data: res } = await this.$http.post("users", userinfo);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.$refs.addFormRef.resetFields();
        this.getUsersList();
      });
    },
    // 取消添加用户
    cancelAddUser() {
      this.addVisible = false;
      this.$refs.addFormRef.resetFields();
    },
    // 删除用户
    delectUser(id) {
      let thisID = id;
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/` + id);
          console.log(res);
          if (res.meta.status !== 200)
            return this.$message.error("删除用户失败");
          this.getUsersList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 打开修改用户弹出框并且渲染数据
    async operate(id) {
      this.operateUser = true;
      const { data: res } = await this.$http.get(`users/` + id);
      if (res.meta.status !== 200) return this.$message.error("查询用户失败");
      this.temporaryuser = res.data;
    },
    // 修改用户数据
    operateUsers() {
      this.$refs.temporaryuserRef.validate(async config => {
        if (!config) return;
        const { data: res } = await this.$http.put(
          `users/` + this.temporaryuser.id,
          this.temporaryuser
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改用户信息失败");
        this.$message.success("修改用户信息成功");
        this.getUsersList();
        this.operateUser = false;
      });
    },
    close() {
      this.$refs.temporaryuserRef.resetFields();
    },
    //为分配角色添加弹出框和方法
    async setRolesRight(userinfo) {

      this.currentUser = userinfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.roleslist = res.data;

      this.rolesRightVisible = true;
    },
    // 修改用户权限角色
    async changeRoles() {
      // this.$refs.setRolesRef.validate(async item => {
      //   if (item) {
          const { data: res } = await this.$http.put(`users/${this.currentUser.id}/role`,{rid:this.currentRolesValue});
          if(res.meta.status!==200)return this.$message.error('设置用户角色失败')
          this.$message.success('设置用户角色成功');
          this.currentRolesValue=''
          this.getUsersList();
      //   }
      // });

      this.rolesRightVisible = false;
    }
  },
  created() {
    this.getUsersList();
  }
};
</script>
<style lang="less" scoped>
.el-table {
  margin: 15px 0;
}
</style>